const express = require('express');
const router = express.Router();
const { paperModel, adminModel, clazzModel, resultModel, studentModel, questionModel } = require('../model/model')

router.get('/paper', async (req, res) => {

    let { name } = req.query

    let regName = new RegExp(name)
    let queryArr = [{ flag: 2 }]
    if (name) queryArr.push({ name: regName })
    if (queryArr.length === 0) {
        queryArr.push({})
    }

    let data = await paperModel.find({ $and: queryArr })

    let newdata = []
    for (let i = 0; i < data.length; i++) {
        let creator = await adminModel.findOne({ _id: data[i].creator })
        let quer = await questionModel.find({ _id: data[i].questions })

        let obj = {
            _id: data[i]._id,
            name: data[i].name,
            time: data[i].time,
            pass_score: data[i].pass_score,
            out: data[i].out,
            creator: creator.name,
            questions: quer,
            type: data[i].type,
            class: data[i].class,
            publishTime: data[i].publishTime,
            flag: data[i].flag,
        }
        newdata.push(obj)
    }
    res.send({
        code: 200,
        data: newdata
    })
})

router.put('/editPaper', async (req, res) => {
    let body = req.body
    let _id = body._id
    await paperModel.updateOne({ _id: _id }, body)

    console.log(body);


    res.send({
        code: 200,
        message: '修改成功'
    })
})



router.get('/clazz', async (req, res) => {
    let data = await clazzModel.find()
    res.send({
        code: 200,
        data: data
    })
})

router.get('/result', async (req, res) => {

    let data = await resultModel.find()

    let newdata = []

    for (let i = 0; i < data.length; i++) {
        let student = await studentModel.findOne({ _id: data[i].student })
        let clazz = await clazzModel.findOne({ _id: data[i].clazz })
        let paper = await paperModel.findOne({ _id: data[i].paper })

        let obj = {
            _id: data[i]._id,
            student: student,
            clazz: clazz.name,
            paper: paper,
            result: data[i].result,
            score: data[i].score,
            time: data[i].time,
            grade: data[i].grade,
            status: data[i].status
        }
        newdata.push(obj)
    }

    res.send({
        code: 200,
        data: newdata
    })
})

router.put('/editResult', async (req, res) => {
    let { update } = req.body
    console.log(update);

    let _id = update._id
    update.student = update.student._id
    update.clazz = update.clazz._id
    update.paper = update.paper._id
    await resultModel.updateOne({ _id: _id }, { $set: update })
    res.send({
        code: 200,
        message: '修改成功'
    })
})

router.get('/questionModel', async (req, res) => {
    let data = await questionModel.find()
    res.send({
        code: 200,
        data: data
    })
})

module.exports = router;